# coding=utf-8

import datetime
import time

# print datetime.datetime.now().weekday(), datetime.datetime.now().hour
#
# import random
#
# for i in range(10):
#     print random.randint(100, 1000)
#
# print 'http://corgi.pt.miui.com/open-api/build/772180/out/polaris_images_1.1.1_20181229.0000.00_8.0_cn_4fa67f30b9.tgz'.startswith(
#     'http://')
#
# during = time.mktime((datetime.datetime.now() + datetime.timedelta(days=1)).date().timetuple()) - time.mktime(
#     datetime.datetime.now().timetuple())
# print during
# print during / 3600
# print datetime.datetime.now().timetuple()
#
# # print min([])
# print min([2])
# print min([3, 6])
#
# import urllib
#
# # page = urllib.urlopen('http://husky.pt.miui.com/device/info')
# # for line in page.readlines():
# #     print line
#
# print '1234567890'[:-1], '1234567890'[-5:]
#
# print '_' + str(datetime.datetime.now().date()) + '_' + str(datetime.datetime.now().time())
#
# x = []
# x.extend('1')
# print x
#
# print 'task_monkey_2644fefa_2019-01-15 16:34:20.652178'.replace(' ', '_')
#
# import threading
#
# result = False
#
#
# def xx():
#     def kill_monkey():
#         print "xxxxx"
#         global result
#         result = True
#
#     threading.Timer(10, kill_monkey).start()
#
#     print 'yyyyyy'
#     while not result:
#         time.sleep(1)
#     return True
#
#
# print xx()
# print 'zzzzz'

import tarfile, os


def zip_task_files(taskfilepath):
    print taskfilepath
    print os.path.abspath(taskfilepath)
    print os.path.basename(taskfilepath)
    with tarfile.open(os.path.abspath(taskfilepath) + ".tar.gz", "w:gz") as tar:
        tar.add(taskfilepath, arcname=os.path.basename(taskfilepath))


crash_list = [
    './output/results/xiaoai_2019-04-02_10:59:27.123302/2019-04-02/Mi_MIX_3_5G/task_monkey_2275def27d1b_2019-03-12_20:10:41.021704_app_crashcom.android.bluetooth_2018-12-09_11_00_31.252_.txt',
    # './output/results/xiaoai_2019-04-02_10:59:27.123302/2019-04-02/Mi_MIX_3_5G/task_monkey_2275def27d1b_2019-03-12_20:10:41.021704_app_crashcom.android.bluetooth_2018-12-09_11_01_44.112_.txt',
    # './output/results/xiaoai_2019-04-02_10:59:27.123302/2019-04-02/Mi_MIX_3_5G/task_monkey_2275def27d1b_2019-03-12_20:10:41.021704_app_crashcom.android.bluetooth_2019-12-03_04_02_03.885_.txt',
    './output/results/xiaoai_2019-04-02_10:59:27.123302/2019-04-02/Mi_MIX_3_5G/task_monkey_7LEITOFIKZLV55TG_2019-03-26_20:17:35.626962_app_crashcom.android.settings_2019-03-27_07_29_18.352_.txt']

anr_list = [
    './output/results/xiaoai_2019-04-02_10:59:27.123302/2019-04-02/Mi_MIX_3_5G/anr_com.android.settings_2019-03-21_14_25_53.300_.txt']

import re


def analysis_crash_and_anr(crash_files, anr_files):
    filter_anr(anr_files)


# filter_fatal_signal(crash_files)
# filter_fatal_exception(crash_files)
class crash_anr_analysis_obj:
    crash_or_anr_detail = 'crash_or_anr_detail'
    file_name = 'file_name'
    fingerprint = 'fingerprint'
    count = 'count'
    list_of_title = [file_name, fingerprint, count, crash_or_anr_detail]
    dict_desc = {
        file_name: '文件名',
        fingerprint: 'crash或者anr概要',
        count: '个数',
        crash_or_anr_detail: 'crash或者anr详情'
    }


def filter_fatal_signal(crash_files):
    print crash_files
    fatal_signal = re.compile(r'[0-9]{3,5} F ')
    crash_list = []
    for file in crash_files:
        if not file.endswith('.txt'):
            continue
        with open(file, "r") as f:
            crash_unit = []
            collect_continue = False
            distinguish = 0
            for line in f.readlines():
                if 'Fatal signal' in line:
                    distinguish = 'Fatal signal'
                    title = line.split(" : ")[1]
                    collect_continue = True
                    # print "crash_unit", crash_unit
                    if crash_unit:
                        crash_obj['crash_or_anr_detail'] = crash_unit
                        crash_obj['file_name'] = file
                        crash_list.append(crash_obj)
                        # crash_obj = {}

                    identity_split = title.split(' ')
                    identity_split[1 + identity_split.index('tid')] = r'[0-9]{3,5}'
                    identity_split[1 + identity_split.index('pid')] = r'[0-9]{3,5}'
                    regularE = ' '.join(identity_split)

                    if crash_list:
                        # print [obj['fingerprint'] for obj in crash_list]
                        identity_fingerprint = [obj['fingerprint'] for obj in crash_list]
                        # print regularE in identity_fingerprint
                        if regularE in identity_fingerprint:
                            crash_list[identity_fingerprint.index(regularE)]['count'] += 1
                            collect_continue = False
                        else:
                            crash_obj = {}
                            crash_obj['fingerprint'] = regularE
                            crash_obj['count'] = 1
                    else:
                        crash_obj = {}
                        crash_obj['fingerprint'] = regularE
                        crash_obj['count'] = 1

                    crash_unit = []
                if distinguish == 'Fatal signal' and collect_continue and fatal_signal.search(line):
                    crash_unit.append(line)
            if crash_unit:
                if distinguish == 'Fatal signal':
                    crash_obj['crash_or_anr_detail'] = crash_unit
                    crash_obj['file_name'] = file
                    crash_list.append(crash_obj)
            # crash_list.append(crash_unit)
    for i in crash_list:
        print "-----------------------------------------------------"
        print i['fingerprint']
        print i['count']
        print i['crash_or_anr_detail']
    return crash_list


def filter_fatal_exception(crash_files):
    crash_list = []
    crash_unit = []
    fatal_exception = r'[0-9]{3,5} E '
    for file in crash_files:
        if not file.endswith('.txt'):
            continue
        crash_unit = []
        crash_obj = {}
        with open(file, 'r') as f:
            capture = False
            for line in f.readlines():
                if 'FATAL EXCEPTION' in line:
                    capture = True
                    line_split = line.split(' ')
                    seperat = line_split[line_split.index('E') + 1]
                    fatal_exception = r'[0-9]{3,5} E '
                    fatal_exception += line_split[line_split.index('E') + 1]
                    if crash_unit:
                        crash_obj['crash_or_anr_detail'] = crash_unit
                        regularE = ''
                        addif = True
                        for l in crash_unit:
                            if 'Process:' in l:
                                split1 = l.split(seperat)[1].split(' ')
                                split1[1 + split1.index('PID:')] = r'[0-9]{3,5}'
                                regularE += ' '.join(split1)
                            if 'Exception:' in l and 'Caused by' not in l:
                                regularE += l.split(seperat)[1]
                            if 'Exception' in l and 'Caused by' in l:
                                regularE += l.split(seperat)[1]

                        if crash_list:
                            identity_fingerprint = [obj['fingerprint'] for obj in crash_list]
                            if regularE in identity_fingerprint:
                                crash_list[identity_fingerprint.index(regularE)]['count'] += 1
                                addif = False
                            else:
                                crash_obj['fingerprint'] = regularE
                                crash_obj['count'] = 1
                        else:
                            crash_obj['fingerprint'] = regularE
                            crash_obj['count'] = 1
                        if addif:
                            crash_obj['file_name'] = file
                            crash_list.append(crash_obj)
                        crash_obj = {}
                    crash_unit = []
                if capture and re.compile(fatal_exception).search(line):
                    crash_unit.append(line)
    if crash_unit:
        crash_obj['crash_or_anr_detail'] = crash_unit
        regularE = ''
        addif = True
        for l in crash_unit:
            if 'Process:' in l:
                split1 = l.split(seperat)[1].split(' ')
                split1[1 + split1.index('PID:')] = r'[0-9]{3,5}'
                regularE += ' '.join(split1)
            if 'Exception:' in l and 'Caused by' not in l:
                regularE += l.split(seperat)[1]
            if 'Exception' in l and 'Caused by' in l:
                regularE += l.split(seperat)[1]

        if crash_list:
            identity_fingerprint = [obj['fingerprint'] for obj in crash_list]
            if regularE in identity_fingerprint:
                crash_list[identity_fingerprint.index(regularE)]['count'] += 1
                addif = False
            else:
                crash_obj['fingerprint'] = regularE
                crash_obj['count'] = 1
        else:
            crash_obj['fingerprint'] = regularE
            crash_obj['count'] = 1
        if addif:
            crash_obj['file_name'] = file
            crash_list.append(crash_obj)
    for i in crash_list:
        print "-----------------------------------------------------"
        print i['fingerprint']
        print i['count']
        print i['crash_or_anr_detail']
    return crash_list


def filter_anr(anr_files):
    anr_list = []
    anr_unit = []
    fatal_exception = r'[0-9]{3,5} E '
    for file in anr_files:
        if not file.endswith('.txt'):
            continue
        anr_unit = []
        anr_obj = {}
        with open(file, 'r') as f:
            capture = False
            for line in f.readlines():
                if 'ANR in' in line and not line.startswith('ANR in'):
                    capture = True
                    line_split = line.split(' ')
                    fatal_exception = ' '.join(line_split[line_split.index('ANR') - 3: line_split.index('ANR')])
                    if anr_unit:
                        anr_obj['crash_or_anr_detail'] = anr_unit
                        regularE = ''
                        addif = True
                        for l in anr_unit:
                            if 'Reason:' in l:
                                regularE = l.split('Reason:')[1]

                        if anr_list:
                            identity_fingerprint = [obj['fingerprint'] for obj in anr_list]
                            if regularE in identity_fingerprint:
                                anr_list[identity_fingerprint.index(regularE)]['count'] += 1
                                addif = False
                            else:
                                anr_obj['fingerprint'] = regularE
                                anr_obj['count'] = 1
                        else:
                            anr_obj['fingerprint'] = regularE
                            anr_obj['count'] = 1
                        if addif:
                            anr_obj['file_name'] = file
                            anr_list.append(anr_obj)
                        anr_obj = {}
                    anr_unit = []
                if capture and re.compile(fatal_exception).search(line):
                    anr_unit.append(line)
    if anr_unit:
        anr_obj['crash_or_anr_detail'] = anr_unit
        regularE = ''
        addif = True
        for l in anr_unit:
            if 'Reason:' in l:
                regularE = l.split('Reason:')[1]

        if anr_list:
            identity_fingerprint = [obj['fingerprint'] for obj in anr_list]
            if regularE in identity_fingerprint:
                anr_list[identity_fingerprint.index(regularE)]['count'] += 1
                addif = False
            else:
                anr_obj['fingerprint'] = regularE
                anr_obj['count'] = 1
        else:
            anr_obj['fingerprint'] = regularE
            anr_obj['count'] = 1
        if addif:
            anr_obj['file_name'] = file
            anr_list.append(anr_obj)
    for i in anr_list:
        print "-----------------------------------------------------"
        print i['fingerprint']
        print i['count']
        print i['crash_or_anr_detail']
    return anr_list
# zip_task_files("./output/results/_2019-04-01_17:41:01.781605/2019-04-01/Mi_MIX_3_5G")
